package com.imooc.zk.demo;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class ZKGetNodeData implements Watcher {

	public static String zkServerPath = "47.104.64.192:2181";
	public static final Integer timeout = 5000;
	public static Stat stat;
	private ZooKeeper zookeeper = null;
	private static CountDownLatch countDown = new CountDownLatch(1);

	public ZKGetNodeData(String zkserverpath) {

		try {
			zookeeper = new ZooKeeper(zkserverpath, timeout, new ZKNodeOperator());
		} catch (IOException e) {
			e.printStackTrace();
			if (zookeeper != null) {
				try {
					zookeeper.close();
				} catch (InterruptedException e1) {
					e1.printStackTrace();
				}
			}
		}
	}

	public ZKGetNodeData() {
	}

	public static void main(String[] args) throws Exception {
		ZKGetNodeData zkServer = new ZKGetNodeData(zkServerPath);

		/**
		 * 参数： path：父节点路径 watch：true或者false，注册一个watch事件
		 */
		// List<String> strChildList = zkServer.getZookeeper().getChildren("/imooc",
		// true);
		// for (String s : strChildList) {
		// System.out.println(s);
		// }

		// 异步调用
		String ctx = "{'callback':'ChildrenCallback'}";
	    zkServer.getZookeeper().getChildren("/imooc", true, new ChildrenCallBack(),ctx);
		zkServer.getZookeeper().getChildren("/imooc", true, new Children2CallBack(), ctx);

		countDown.await();
	}

	private ZooKeeper getZookeeper() throws IOException {
		ZooKeeper keeper = new ZooKeeper(zkServerPath, timeout, new ZKGetNodeData());
		return keeper;
	}

	@Override
	public void process(WatchedEvent event) {
		try {
			if (event.getType() == EventType.NodeDataChanged) {
				ZKGetNodeData zkServer = new ZKGetNodeData(zkServerPath);
				byte[] resByte;
				resByte = zkServer.getZookeeper().getData("/imooc", false, stat);
				String result = new String(resByte);
				System.out.println("更改后的值：" + result);
				System.out.println("版本号变化dversion：" + stat.getVersion());
				countDown.await();
			} else if (event.getType() == EventType.NodeCreated) {

			} else if (event.getType() == EventType.NodeChildrenChanged) {

			} else if (event.getType() == EventType.NodeDeleted) {

			}
		} catch (KeeperException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
